package com.lam.code.controller;

import com.lam.code.base.domain.ReturnT;
import com.lam.code.configuration.shiro.JWTUtil;
import com.lam.code.dto.UserDto;
import com.lam.code.entity.User;
import com.lam.code.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description 登录控制器
 * @Author Lam
 * @Date 2019/12/27 14:58
 */
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param loginUser
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ReturnT login(@RequestBody UserDto loginUser, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginUser.getUsername(),loginUser.getPassword());
        try {
            subject.login(usernamePasswordToken);
        } catch (IncorrectCredentialsException e) {
            throw new AuthenticationException("用户名或密码错误");
        }
        User user = (User) subject.getPrincipal();
        String token = JWTUtil.sign(user.getId());
        response.setHeader("x-auth-token", token);

        return ReturnT.success("登录成功");
    }

    /**
     * 登出
     * @return
     */
    @GetMapping("logout")
    public ReturnT logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipal() != null){
            User user = (User) subject.getPrincipals().getPrimaryPrincipal();
            userService.deleteLoginUserInfo(user.getId());
        }

        subject.logout();
        return ReturnT.success("登出成功");
    }



}
